package com.changcheng.project.yuminsi.commons;

import com.changcheng.project.yuminsi.error.BusinessException;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author yuminsi
 * @description
 * @date 2020/8/20 17:07
 * @since
 */
@Component
public class RestTemplateCommons {
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateCommons.class);

    @Autowired
    private RestTemplate restTemplate;

    public String getRcos(StringBuilder sb) {
        //HTTP请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("text/xml;charset=UTF-8");
        headers.setContentType(mediaType);
        HttpEntity<String> entity = new HttpEntity<>(sb.toString(), headers);

        //访问第三方路径
        String url = "http://106.39.79.26:51881/Service.asmx";
        //调用第三方接口
        String resultStr = restTemplate.postForObject(url, entity, String.class);
        logger.info("resultStr: {}", resultStr);

        //转换返回结果中的特殊字符，返回的结果中会将xml转义，此处需要反转移
        String tmpStr = StringEscapeUtils.unescapeXml(resultStr);
        String resultXml = StringUtils.substringBetween(tmpStr, "<RCos>", "</RCos>");
        String[] split = resultXml.split(":");
        String logo = split[0];
        String rCos = split[1];
        if (!"00".equals(logo)) {
            throw new BusinessException(logo, rCos);
        }
        return rCos;
    }
}
